import { NextRequest, NextResponse } from "next/server";
import fs from "fs";
import path from "path";

// 默认设置
const defaultSettings = {
  apiEndpoint: "http://localhost:11434/api/chat",
  model: "deepseek-r1:1.5b",
  temperature: 0.7,
  maxTokens: 2048,
  topP: 0.9,
  streamingEnabled: true
};

// 设置文件路径
const settingsPath = path.resolve(process.cwd(), "settings.json");

// 确保设置文件存在
if (!fs.existsSync(settingsPath)) {
  try {
    fs.writeFileSync(settingsPath, JSON.stringify(defaultSettings, null, 2), "utf8");
    console.log("已创建默认设置文件");
  } catch (error) {
    console.error("创建设置文件失败:", error);
  }
}

// 获取设置
export async function GET() {
  try {
    if (!fs.existsSync(settingsPath)) {
      return NextResponse.json(defaultSettings);
    }
    
    const settingsData = fs.readFileSync(settingsPath, "utf8");
    const settings = JSON.parse(settingsData);
    
    // 确保model字段存在
    if (!settings.model) {
      settings.model = defaultSettings.model;
    }
    
    // 确保API端点格式正确
    if (!settings.apiEndpoint || typeof settings.apiEndpoint !== "string") {
      settings.apiEndpoint = defaultSettings.apiEndpoint;
    } else if (!settings.apiEndpoint.includes("/api/")) {
      // 添加标准API路径
      if (settings.apiEndpoint.endsWith("/")) {
        settings.apiEndpoint = `${settings.apiEndpoint}api/chat`;
      } else {
        settings.apiEndpoint = `${settings.apiEndpoint}/api/chat`;
      }
    }
    
    return NextResponse.json(settings);
  } catch (error) {
    console.error("读取设置失败:", error);
    return NextResponse.json(defaultSettings);
  }
}

// 更新设置
export async function POST(req: NextRequest) {
  try {
    const requestData = await req.json();
    
    // 验证设置
    const validatedSettings = {
      apiEndpoint: typeof requestData.apiEndpoint === "string" ? requestData.apiEndpoint : defaultSettings.apiEndpoint,
      model: typeof requestData.model === "string" ? requestData.model : defaultSettings.model,
      temperature: typeof requestData.temperature === "number" && requestData.temperature >= 0 && requestData.temperature <= 2 
        ? requestData.temperature 
        : defaultSettings.temperature,
      maxTokens: typeof requestData.maxTokens === "number" && requestData.maxTokens > 0 
        ? requestData.maxTokens 
        : defaultSettings.maxTokens,
      topP: typeof requestData.topP === "number" && requestData.topP >= 0 && requestData.topP <= 1 
        ? requestData.topP 
        : defaultSettings.topP,
      streamingEnabled: typeof requestData.streamingEnabled === "boolean" 
        ? requestData.streamingEnabled 
        : defaultSettings.streamingEnabled
    };
    
    // 确保API端点格式正确
    if (!validatedSettings.apiEndpoint.includes("/api/")) {
      // 添加标准API路径
      if (validatedSettings.apiEndpoint.endsWith("/")) {
        validatedSettings.apiEndpoint = `${validatedSettings.apiEndpoint}api/chat`;
      } else {
        validatedSettings.apiEndpoint = `${validatedSettings.apiEndpoint}/api/chat`;
      }
    }
    
    // 保存设置
    fs.writeFileSync(settingsPath, JSON.stringify(validatedSettings, null, 2), "utf8");
    
    // 更新环境变量
    process.env.API_ENDPOINT = validatedSettings.apiEndpoint;
    process.env.MODEL = validatedSettings.model;
    process.env.TEMPERATURE = String(validatedSettings.temperature);
    process.env.MAX_TOKENS = String(validatedSettings.maxTokens);
    process.env.TOP_P = String(validatedSettings.topP);
    process.env.STREAMING_ENABLED = String(validatedSettings.streamingEnabled);
    
    return NextResponse.json({ success: true, settings: validatedSettings });
  } catch (error) {
    console.error("保存设置失败:", error);
    return NextResponse.json(
      { error: error instanceof Error ? error.message : "保存设置时出错" },
      { status: 500 }
    );
  }
} 